import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/RegisterView.vue')
  },
  {
    path: '/books',
    name: 'books',
    component: () => import('../views/BooksListView.vue')
  },
  {
    path: '/books/:id',
    name: 'bookDetail',
    component: () => import('../views/BookDetailView.vue')
  },
  {
    path: '/center',
    name: 'center',
    component: () => import('../views/UserCenterView.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 全局前置守卫：需要登录的路由拦截
router.beforeEach((to, _from, next) => {
  if (to.meta && (to.meta as any).requiresAuth) {
    const token = localStorage.getItem('token')
    if (!token) {
      next({ path: '/login', query: { redirect: to.fullPath } })
      return
    }
  }
  next()
})

export default router
